<template>
  <div v-loading="loadingPage">

    <page-main style="overflow-x:hidden">
      <el-form ref="formRef" :model="dataForm" :inline="true">
        <el-card class="box-card">
          <el-form-item label="名称：" prop="budgetTemplateId">
            {{ budgetVO.budgetName }}
          </el-form-item>
          <el-form-item label="年份：" prop="years">
            {{ budgetVO.years }}
          </el-form-item>
          <el-form-item label="周期：" prop="cycleType">
            {{ statusText([...TIME_WEEK_LIST, ...WEEK_LIST], budgetVO.cycleType) }}
          </el-form-item>
          <el-form-item label="新增方式：" prop="budgetTemplateId">
            {{ budgetVO.budgetTemplateId ? '预算模板' : '自定义' }}
          </el-form-item>

          <el-form-item label="模板名称：" prop="budgetTemplateName">
            {{ budgetVO.budgetTemplateName }}
          </el-form-item>
          <!-- <el-form-item label="控制方式：" prop="controlBy">
            {{ statusText(CTROL_METHOD_LIST, budgetVO.controlBy) }}
          </el-form-item>

          <el-form-item label="预算类型：" prop="budgetType">
            {{ statusText(BUDGET_TYPE_LIST, budgetVO.budgetType) }}
          </el-form-item>
          <el-form-item label="预算结转：" prop="budgetRollEnabled">
            {{ budgetVO.budgetRollEnabled ? '是' : '否' }}
          </el-form-item> -->

        </el-card>

        <div class="search-box">
          <el-row>
            <el-col :span="20">
              <el-form :model="formInline" @onReset="searchReset" ref="formInlineRef">
                <el-form-item label="预算科目" prop="subject">
                  <el-select v-model="formInline.subject" filterable multiple collapse-tags clearable style="width:350px">
                    <el-option v-for="item in useSubjectList" :key="item.id" :label="item.label + item.categoryCode"
                      :value="item.id">
                      <span style="float: left">{{ item.label }}</span>
                      <span style="float: right; font-size: 13px;">{{ item.categoryCode }}</span>
                    </el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label="费用类型" prop="feeType">
                  <el-select v-model="formInline.feeType" filterable multiple collapse-tags clearable style="width:350px">

                    <el-option v-for="item in feeTypeOptions" :key="item.id" :label="item.typeName + item.typeCode"
                      :value="item.id">
                      <span style="float: left">{{ item.typeName }}</span>
                      <span style="float: right; font-size: 13px;">{{ item.typeCode }}</span>
                    </el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label="">
                  <el-button type="primary" @click="searchClick()">查询</el-button>
                  <el-button @click="searchReset()">重置</el-button>
                </el-form-item>
              </el-form>
            </el-col>
            <el-col :span="4" style="text-align: right;">
              <el-button @click="router.go(-1)">返 回</el-button>
              <el-button @click="saveInfo" type="primary" v-if="pageType != 'look'" :loading="loading">保 存</el-button>
            </el-col>
          </el-row>

        </div>
        <el-row class="head-info">
          <el-col :span="24">
            <el-button @click="addSubject" type="primary">新增</el-button>
            <el-button @click="exportOut" type="primary" :disabled="budgetCategoryVOS.length == 0">导 出
            </el-button>
            <el-button @click="importHandle" type="primary" v-if="pageType != 'look'"
              :disabled="budgetCategoryVOS.length == 0">导 入
            </el-button>


          </el-col>
        </el-row>

        <div class="subject-con">
          <el-row :gutter="80">
            <!-- <el-col :span="8">
              
             <div class="subject-tree" >
                <SubjectTree :dataSource="dataSource" @on-update="updateSubject" :interFaceInfo="interFaceInfo"
                  @on-nodeClick="nodeClick" :budgetTemplateId="budgetVO.budgetTemplateId"></SubjectTree>
              </div> 
          
            </el-col>  -->

            <el-col :span="24" style="margin-top:15px">

              <div class="table">


                <table class="table-box">
                  <thead class="fixed-top">
                    <tr>
                      <th style="min-width:180px" class="fixed-left">维度</th>
                      <th style="min-width:180px" v-for="(item, index) in listConfig" :key="index">{{ item.stringTime }}
                      </th>
                      <th style="min-width:180px" class="fixed">合计</th>
                    </tr>
                  </thead>
                  <tbody>

                    <transition-group class="transition-wrapper" name="sort">
                      <tr v-for="(item, index) in showTableData" :key="index">
                        <td class="fixed-left">
                          <div :class="[item.children ? 'small-title' : 'child-title']" class="table-title">
                            <span> {{ item.label }} </span>
                            <div class="btn-area">
                              <el-button @click="editRow(item, index)" link v-if="!item.children">编辑</el-button>
                              <el-button @click="delRow(item, index)" link
                                v-if="!item.children && item.addType">删除</el-button>
                            </div>
                          </div>
                        </td>

                        <td v-for="(itemTd, indexTd) in item.budgetDetailUpdateParams" :key="indexTd"
                          :style="{ 'width': itemTd.width ? itemTd.width : 'auto' }">
                          <div>
                            <p class="money" v-if="item.children" style="font-weight:bold">
                              {{ MoneyFormat(Number(itemTd.totalBudget).toFixed(2)) }}</p>
                            <p class="money 11" v-else>
                              <el-input type="number" placeholder="请输入" v-model="itemTd.totalBudget"
                                :disabled="pageType == 'look'" style="width:140px"
                                @blur="changeMoney(itemTd.totalBudget, indexTd, index, item, itemTd)">
                              </el-input>

                            </p>
                            <p class="use" v-if="itemTd.id">已使用额度 : <span class="link" @click="toLink('USE', itemTd)">{{
                              MoneyFormat(Number(itemTd.usedBudget || 0).toFixed(2)) }}</span></p>
                            <p class="use" v-else>已使用额度 : {{ MoneyFormat(Number(itemTd.usedBudget).toFixed(2))
                            }}</p>

                            <p class="use" v-if="pageType == 'look' && itemTd.id">可使用额度 :{{
                              MoneyFormat(Number(itemTd.availableBudget).toFixed(2))
                            }}</p>
                            <p class="use" v-if="pageType == 'look' && itemTd.id">调整总额 :
                              <span class="link" @click="toLink('ADJUSTMENT', itemTd)">{{
                                MoneyFormat(Number(itemTd.adjustmentBudget || 0).toFixed(2))
                              }}</span>
                            </p>

                          </div>
                        </td>
                        <td class="fixed" style="min-width:180px">

                          <el-popover placement="left" :width="200" trigger="hover">
                            <template #reference>
                              <div style="width:100%;font-weight:bold">
                                <p>{{ MoneyFormat(Number(item.totalMoney || 0).toFixed(2))
                                }}</p>
                                <p class="use">已使用:{{ MoneyFormat(Number(item.totalUsedBudget || 0).toFixed(2))
                                }}</p>
                              </div>

                            </template>
                            <!-- <div class="privew">
                              <ul>
                                <li>
                                  <p>上一版预算:</p>
                                  <p>{{
                                    MoneyFormat(totalMoneyComputed(item.detailHistoryVOS))
                                  }}
                                  </p>
                                </li>
                                <li>
                                  <p>预算变动:</p>
                                  <p :style="{ color: item.color }">
                                    {{ MoneyFormat(moneyChange(item.totalMoney, item.detailHistoryVOS, index))}}

                                  </p>
                                </li>
                              </ul>
                            </div> -->
                          </el-popover>
                        </td>

                      </tr>
                    </transition-group>
                  </tbody>
                </table>
              </div>
            </el-col>
          </el-row>
        </div>


      </el-form>
    </page-main>

    <importForm :dialog-visible="dialogVisibleExport" :acceptOption="acceptOption" @on-submit="exportIn"
      @handle-close="handleClose" :showDown="true" @downFile="downFileTemplate" />
    <subjectlLatitude :dialogVisible="dialogVisible" @handle-close="handleClose" v-if="dialogVisible"
      @on-update="updateSubject" :nodeData="nodeData" :budgetTemplateId="budgetVO.budgetTemplateId">
    </subjectlLatitude>

    <editSubjectAttbute :dialogVisible="dialogVisibleSubject" :formDisabled="formDisabled" :budgetVO="budgetVO"
      :editRowInfo="editRowInfo" :type="pageType" @handleClose="handleClose" @on-update="updateEditSubject">
    </editSubjectAttbute>
  </div>
</template>
<script setup>

import { yearFun, singleArr, treeData, unique } from '@/util/index'
import SubjectTree from '@/components/SubjectTree/index.vue';
import { TIME_WEEK_LIST, WEEK_LIST, BUDGET_TYPE_LIST, CTROL_METHOD_LIST } from './config'
import { statusText } from '@/util/index'
import { ElMessage } from 'element-plus';
import { downloadFile } from '@/util/downFile'
import api from '@/api/index'
import dayjs from 'dayjs'
import { MoneyFormat } from '@/util/filterConfig'
import { dataListStore } from '@/store/modules/pubiclDataList'
import subjectlLatitude from '@/components/SubjectTree/subjectlLatitude.vue'
import editSubjectAttbute from './editSubjectAttbute.vue'

const route = useRoute()
const router = useRouter()
const dataForm = ref({
  type: '',
  afterExceed: '',
  floatUpwardAmount: 0,
  limitExceed: '0'
})

const ctrolMehtodList = ref([
  { label: '周期', value: '1' },
  { label: '自定义时间范围', value: '2' }
])

const type = ref('one')

const dialogVisible = ref(false)

const feeTypeOptions = ref([])

const dataStore = dataListStore()

const editRowInfo = ref({})


const formDisabled = ref(false)

const formRef = ref(null)

const loadingPage = ref(false)

const dialogVisibleExport = ref(false)

const dialogVisibleSubject = ref(false)

const acceptOption = ref('.xls,.xlsx') //导入格式

const importLoading = ref(false)


const listConfig = ref([])

// 科目树删除接口
const interFaceInfo = ref({
  url: 'accoutnDel',//接口名称
  params: {

  },// 参数
  fileName: 'account'
})
const tableData = ref([])

// 最高层级写死，叫如果预算类型是费用预算就显示成本中心 如果是项目 预算 就叫项目预算
const dataSource = ref([])

const lantId = ref("")

// 年份
const yearOptions = yearFun()

const budgetVO = ref({})

const pageId = ref('')

const budgetCategoryVOS = ref([])

const pageType = ref('edit')

const costCenterName = ref('') // 成本中心名称

const loading = ref(false)

const showTableData = ref([])

const useSubjectList = ref([])

const formInlineRef = ref(null)

const curParentBudgetCategoryId = ref('0')

const nodeData = ref({
  budgetCategoryId: 0
})

const formInline = ref({
  subject: '',
  feeType: ''
})

watch(() => tableData.value, (newVal) => {
  console.log(newVal, 'tableData数据')
  showTableData.value = newVal


})


const totalMoneyComputed = (list = []) => {
  let total = 0
  list.forEach((item) => {
    total += Number(item.totalBudget)
  })

  return total.toFixed(2)
}
const moneyChange = (totalMoney = 0, list, index) => {
  let total = Number(Number(totalMoney) - Number(totalMoneyComputed(list))).toFixed(2)
  let color = 'red'
  if (total < 0) {
    color = 'green'
  }
  tableData.value[index]['color'] = color

  return total
}

onMounted(() => {
  const { id, type, centerName } = route.query
  pageId.value = id
  pageType.value = type
  costCenterName.value = centerName
  getDetail()
  getFeeTypeList()


})


const getDetail = () => {
  loadingPage.value = true

  api.budgetManger.budgetMangerLookDetail({ id: pageId.value }).then(res => {
    budgetVO.value = res.budgetVO


    let subjectList = []
    if (res.budgetCategoryVOS.length == 0) {
      getSubjectId()
    } else {
      // 根据关联关系字段categoryRelationId组装成所需数据

      res.budgetCategoryVOS.forEach(item => {
        if (!item['detailHistoryVOS']) item['detailHistoryVOS'] = []
        item['id'] = item['categoryRelationId']
        item.limitExceed = item.limitExceed ? String(item.limitExceed) : '0'

        res.feeTypeVOS.forEach(feeItem => {
          if (item.categoryRelationId == feeItem.categoryRelationId) {
            if (!item['feeTypeRelationParams']) item['feeTypeRelationParams'] = []
            item['feeTypeRelationParams'] = [...item['feeTypeRelationParams'], {
              orgCode: feeItem.orgCode,
              feeTypeId: feeItem.id,
              categoryRelationId: feeItem.categoryRelationId,
              id: feeItem.id,
              feeTypeRelationId: feeItem.feeTypeRelationId
            }]
          }
        })
        //排序
        res.detailVOS = res.detailVOS.sort((a, b) => {
          return new Date(a.startTime).getTime() - new Date(b.startTime).getTime()
        })
        // 预算详情数据即右边表格数据
        res.detailVOS.forEach(detailtem => {
          detailtem['startTime'] = dayjs(detailtem['startTime']).format('YYYY-MM-DD HH:mm:ss')
          detailtem['endTime'] = dayjs(detailtem['endTime']).format('YYYY-MM-DD HH:mm:ss')
          detailtem['budgetDetailId'] = detailtem.id
          if (item.categoryRelationId == detailtem.budgetCategoryRelationId) {
            if (!item['budgetDetailUpdateParams']) item['budgetDetailUpdateParams'] = []
            let total = 0
            item['budgetDetailUpdateParams'].forEach(childItem => {
              item['totalMoney'] = total += Number(childItem.totalBudget)
            })
            item['totalMoney'] = total.toFixed(2)
            item['budgetDetailUpdateParams'] = [...item['budgetDetailUpdateParams'], detailtem]


          }
        })
        // 历史版本数据
        res.detailHistoryVOS.forEach(hisItem => {
          if (item.budgetCategoryId == hisItem.budgetCategoryId) {
            // 当前级匹配自己的上一个版本数据
            item['detailHistoryVOS'] = [...item['detailHistoryVOS'], hisItem]
          }
          if (item.budgetCategoryId == hisItem.parentBudgetCategoryId) {
            // 父级上一版本费用总和
            item['detailHistoryVOS'] = [...item['detailHistoryVOS'], hisItem]
          }
        })
        item['label'] = item['categoryName']

        if (item.parentBudgetCategoryId == '0') {
          item['detailHistoryVOS'] = res.detailHistoryVOS
          item['label'] = costCenterName.value
          curParentBudgetCategoryId.value = item.budgetCategoryId
        }


        if (item['feeTypeRelationParams'] && item['feeTypeRelationParams'].length > 0) item['isShowAddBtn'] = true
        // 如果是模板非自定义，则不能显示新增 删除按钮

        if (pageType.value == 'look') {
          // 隐藏 树的新增 删除按钮
          item['isShowAddBtn'] = true
          item['isShowDelBtn'] = true
        }
        item['isShowDelBtn'] = true

        if (!item['budgetDetailUpdateParams']) {
          // 解决detailVOS为空 或者顶级无budgetDetailUpdateParams 填充右边界面 td
          item['budgetDetailUpdateParams'] = res.headList.map(mapItem => {
            return {
              budgetCategoryRelationId: item.categoryRelationId || null,
              startTime: mapItem.startTime,
              endTime: mapItem.endTime,
              totalBudget: 0,
              stringTime: mapItem.stringTime
            }
          })
        }
        // 当后端返回数据与表头数据长度不相等时需前端补充数据占位，比如表头有6条数据，后端只返回了一条数据
        let haveTimeArr = []
        item['budgetDetailUpdateParams'].forEach(itemDetail => {
          haveTimeArr.push(itemDetail.stringTime)
        })
        res.headList.forEach((itemHead, headIndex) => {
          if (!haveTimeArr.includes(itemHead.stringTime)) {

            item['budgetDetailUpdateParams'].splice(headIndex, 0, {
              budgetCategoryRelationId: item.categoryRelationId || null,
              startTime: itemHead.startTime,
              endTime: itemHead.endTime,
              totalBudget: 0,
              stringTime: itemHead.stringTime
            })
          }

        })
        if (item['parentBudgetCategoryId'] != '0') {
          subjectList.push(item)
        }

      })
      console.log(res.budgetCategoryVOS, 'res.budgetCategoryVOS')
      let source = treeData(res.budgetCategoryVOS, 'budgetCategoryId', 'parentBudgetCategoryId', '0')
      // 回显的时候对已选择的科目新增的时候不能再次进行选择
      dataStore.submitSubjectId(res.budgetCategoryVOS.filter(subjectItem => subjectItem.parentBudgetCategoryId != '0'))
      dataSource.value = source

    }

    budgetCategoryVOS.value = res.budgetCategoryVOS
    listConfig.value = res.headList

    nodeClick([dataSource.value[0]])
    loadingPage.value = false
    useSubjectList.value = subjectList
    dataStore.setAllfeeTypeVOList(res.feeTypeVOS.map(item => item.id))


  })
}

const findSubject = (subject) => {
  let result = []
  subject.forEach(item => {
    tableData.value.forEach(itemTwo => {
      if (item == itemTwo.id) result.push(itemTwo)
    })
  })
  return result
}

const feeTypeSearch = (feeType, list) => {
  let result = []
  feeType.forEach(item => {
    list.forEach(itemTwo => {
      if (itemTwo.feeTypeRelationParams && itemTwo.feeTypeRelationParams.length > 0) {
        itemTwo.feeTypeRelationParams.forEach(itemThree => {
          if (itemThree.id == item) result.push(itemTwo)
        })
      }
    })

  })
  return result
}
const searchClick = () => {
  console.log(formInline.value)
  const { subject, feeType } = formInline.value
  let result = []

  if (subject.length > 0 && feeType.length == 0) {
    // 选择了科目
    result = findSubject(subject)

  } else if (subject.length == 0 && feeType.length > 0) {
    // 选择了费用类型
    result = feeTypeSearch(feeType, tableData.value)

  } else if (subject.length > 0 && feeType.length > 0) {
    // 选择了科目和费用类型
    let subjectResult = findSubject(subject)
    result = feeTypeSearch(feeType, subjectResult)

  } else {
    // 科目和费用类型都没有选择
    result = tableData.value
  }
  result = unique(result, 'id')

  showTableData.value = result
}

//删除
const delRow = (row) => {
  console.log(row, '删除')
  let findSub = useSubjectList.value.findIndex(item => item.id == row.id)
  if (findSub > -1) useSubjectList.value.splice(findSub, 1)

  let findSourceIndex = dataSource.value[0].children.findIndex(item => item.id == row.id)
  if (findSourceIndex > -1) {
    dataSource.value[0].children.splice(findSourceIndex, 1)
  }
  let tableList = JSON.parse(JSON.stringify(tableData.value))
  let findIndex = tableList.findIndex(item => item.id == row.id)

  if (findIndex > -1) {
    tableList.splice(findIndex, 1)
    tableData.value = tableList
  }

  let subjectIds = [...dataStore.selectAllSubjectList]
  let findSubIdIndex = subjectIds.findIndex(item => item.id == row.id)
  if (findSubIdIndex > -1) {
    subjectIds.splice(findSubIdIndex, 1)
    dataStore.submitSubjectId(subjectIds)
  }

  // 清空预算科目对应的数据
  let subIndex = formInline.value.subject.findIndex(item => item == row.id)

  if (subIndex > -1) {
    formInline.value.subject.splice(subIndex, 1)
    searchClick()
  }


}
const searchReset = () => {
  formInlineRef.value.resetFields()
  searchClick()

}

// 编辑
const editRow = (row) => {
  console.log('编辑row', row)
  editRowInfo.value = {
    type: row.feeTypeRelationParams.map(item => item.feeTypeId),
    afterExceed: row.afterExceed,
    limitExceed: row.limitExceed,
    floatUpwardAmount: row.floatUpwardAmount,
    id: row.id,
    orgCode: row.orgCode

  }
  if (row.addType == 'add') {
    formDisabled.value = false
  } else {
    formDisabled.value = true
  }

  dialogVisibleSubject.value = true

}
const updateEditSubject = (row) => {
  console.log('更关联', row, 'tableData.value', tableData.value)
  let curTableData = JSON.parse(JSON.stringify(tableData.value))
  let findIndex = curTableData.findIndex(item => item.id == row.id)
  let findSourceIndex = dataSource.value[0].children.findIndex(item => item.id == row.id)
  if (findIndex > -1) {
    const data = {
      ...curTableData[findIndex],
      ...row,
      parentBudgetCategoryId: curParentBudgetCategoryId.value
    }
    curTableData[findIndex] = data
    tableData.value = curTableData


  }
  if (findSourceIndex > -1) {
    const dataOne = {
      ...dataSource.value[0].children[findSourceIndex],
      ...row,
      parentBudgetCategoryId: curParentBudgetCategoryId.value
    }

    dataSource.value[0].children[findSourceIndex] = dataOne

  }
  console.log(tableData.value, 'tableData.value')
}



// 获取费用类型
const getFeeTypeList = () => {
  const params = {
    pageNum: 1,
    pageSize: 10000,
    enabled: true
  }
  api.feeConfig.feeTypeList(params).then(res => {
    feeTypeOptions.value = res.list
  })

}
// 获取树的顶级 id
const getSubjectId = () => {
  api.budgetConfig.budgetSubjectId().then(res => {
    lantId.value = res
    dataSource.value = [
      {
        label: budgetVO.value.budgetType == 'COST' ? '成本中心' : '项目预算',
        parentBudgetCategoryId: '0',
        "afterExceed": "",
        "budgetCategoryId": res,
      }]

  })
}


const handleClose = () => {
  dialogVisibleExport.value = false
  dialogVisible.value = false
  dialogVisibleSubject.value = false
}

const importHandle = () => {
  importLoading.value = true
  dialogVisibleExport.value = true
}


const nodeClick = ([data, node, obj]) => {
  if (JSON.stringify(data) == '{}' || !data) return
  if (data.parentBudgetCategoryId == '0' && !data.children) return


  let ids = []
  if (!data.limitExceed) data.limitExceed = ''
  if (data['feeTypeRelationParams']) { data['feeTypeRelationParams'].forEach(item => ids.push(item.feeTypeId)) }

  addDetailParmas(...dataSource.value)
  // dataForm.value['type'] = ids
  // dataForm.value['afterExceed'] = data['afterExceed'] || ''
  // dataForm.value['floatUpwardAmount'] = data['floatUpwardAmount'] || ''
  // dataForm.value['limitExceed'] = data['limitExceed'] || ''

  if (data.parentBudgetCategoryId != '0' && !data['children']) nodeData.value = data
  if (data.children && data.children.length > 0) {
    tableData.value = [data, ...singleArr(data.children)]
    //formDisabled.value = true
    nodeData.value = {}
  } else {
    if (!budgetVO.value.budgetTemplateId) formDisabled.value = false

    tableData.value = [data]
  }
  endlongCouputedMoney(tableData.value)

}

const addSubject = () => {
  dialogVisible.value = true
}

const toLink = (type, { budgetNo, startTime, endTime, budgetCategoryRelationId, budgetDetailId }) => {
  console.log(budgetDetailId, 'budgetDetailId')
  const linkObj = {
    'USE': 'budgetClearOrder',
    'ADJUSTMENT': 'budgetChangeDetail'
  }
  let query = {
    budgetNo,
    type,
    budgetCategoryRelationId
  }
  if (type == 'USE') {
    query.startTime = startTime
    query.endTime = endTime
  } else {
    query.budgetDetailId = budgetDetailId
  }
  router.push({
    name: linkObj[type],
    query
  })
}
// 手动添加 budgetDetailUpdateParams
const addDetailParmas = (data) => {
  let list = [data, ...singleArr(data.children || [])]
  list.forEach((item => {
    if (!item['budgetDetailUpdateParams']) item['budgetDetailUpdateParams'] = []
  }))
  // 自定义模板
  listConfig.value.forEach(item => {
    list.forEach(((itemList, index) => {
      itemList['totalBudget'] = 0
      if (itemList['budgetDetailUpdateParams'].length < listConfig.value.length) {
        itemList['budgetDetailUpdateParams'].push({
          budgetCategoryRelationId: null,
          startTime: item.startTime,
          endTime: item.endTime,
          totalBudget: 0
        })
      }
    }))
  })
  return list
}

// 更新数据
const updateSubject = (data) => {
  console.log(dataSource.value)
  if (!dataSource.value[0].children) dataSource.value[0].children = []
  data.forEach(item => {
    item.parentBudgetCategoryId = curParentBudgetCategoryId.value
  })
  dataStore.submitSubjectId([...dataStore.selectAllSubjectList, ...data])
  let curTableData = JSON.parse(JSON.stringify(tableData.value))
  let index = 1
  for (let k in curTableData) {
    if (!curTableData[k].children) {
      index = k
      break;
    }
  }
  if (curTableData.length == 0) {
    tableData.value = data
  } else {
    curTableData.splice(index, 0, ...data)
    console.log(curTableData, 'curTableDatacurTableData')
    tableData.value = curTableData
  }


  dataSource.value[0].children.push(...data)
  console.log(data, '更新科目数据', tableData.value)
  useSubjectList.value.unshift(...data)
  // if (dataSource.value[0]) {
  //   nodeClick([dataSource.value[0]])
  // }

  addDetailParmas(...dataSource.value)

}



// 导出
const exportOut = () => {
  api.budgetConfig.budgetDownLoadExcel({ id: pageId.value }).then((res) => {
    downloadFile(res, budgetVO.value.budgetName, 'xlsx')
    ElMessage({
      type: 'success',
      message: '下载成功!'
    });

  })
}
// 导入数据处理
const exportInDataDeal = (needData) => {
  let needTableData = [...singleArr(dataSource.value || [])]
  needData.forEach(needItem => {
    needTableData.forEach(item => {
      if (needItem['维度名称'] == item.label && item.parentBudgetCategoryId != '0' && item.budgetDetailUpdateParams) {
        item.budgetDetailUpdateParams.forEach(detailItem => {
          detailItem['totalBudget'] = needItem[detailItem.stringTime] || 0
        })
      }
    })
  })
  nodeClick([dataSource.value[0]])
}

// 导入>>此导入是在excel中填写总使用金额 totalBudget,非添加新的科目或者,删除已有科目
const exportIn = (val) => {
  let fd = new FormData()
  fd.append('file', val.file)
  api.budgetConfig.budgetExportIn(fd, pageId.value).then((res) => {
    ElMessage({
      type: 'success',
      message: '导入成功!'
    });
    dialogVisibleExport.value = false
    exportInDataDeal(res)

  })
}

// 下载导入模板
const downFileTemplate = () => {
  api.budgetConfig.budgetExportInTemplate({ id: pageId.value }).then((res) => {
    downloadFile(res, budgetVO.value.budgetName, 'xlsx')
    ElMessage({
      type: 'success',
      message: '下载成功!'
    });

  })
}


// 较验 预算科目维度最底层级必须关联类型和超标限制
const valieateFeeType = () => {
  const feeTreeFn = (arr) => {
    let text = ''
    arr.forEach(item => {
      if ((!item.children || (item.children && item.children.length == 0)) && (item['afterExceed'] == '' || item['limitExceed'] == '' || (item['feeTypeRelationParams'] && item['feeTypeRelationParams'].length == 0))) {
        // 是否是最底层
        ElMessage.error(`请完善 【${item.label}】 的关联费用类型、超标限制、预算控制`)
        throw new Error()
      }
      if (item.children && item.children.length > 0) {
        feeTreeFn(item.children)
      }
    })
  }

  feeTreeFn(dataSource.value)
}
const saveInfo = () => {
  if (!formRef) return
  formRef.value.validate(valid => {
    if (valid) {

      if (!dataSource.value[0]['children']) return ElMessage.error('请添加科目维度')
      valieateFeeType()
      let data = {
        budgetTemplateId: budgetVO.value.budgetTemplateId || null,
        id: pageId.value
      }
      let arr = singleArr(JSON.parse(JSON.stringify(dataSource.value)))

      arr.forEach(item => {
        item['feeTypeRelationUpdateParams'] = item['feeTypeRelationParams'] || []

        item['budgetId'] = pageId.value
        delete item['feeTypeRelationParams']
        if (item.addType && item.addType == 'add') item.id = null
        delete item.children
      })
      data['budgetCategoryRelationUpdateParams'] = arr
      console.log(arr, 'arrr')
      console.log(data, 'data')
      loading.value = true

      api.budgetManger.budgetMangerEdit(data).then(res => {
        router.go(-1)
        ElMessage.success('操作成功')
        loading.value = false
        dataStore.submitSubjectId([])
      }).catch(err => {
        loading.value = false
      })
    } else {
      console.log('error submit!')
      return false
    }
  })
}

const changeMoney = (val, curIndex, parIndex, item, itemTd) => {

  endlongCouputedMoney(tableData.value)

}

// 纵横向计算合计父节点合计
const endlongCouputedMoney = (data) => {

  const treeHandle = (list) => {
    let totalList = []
    let usedBudgetList = []

    list.forEach(item => {
      if (item['children'] && item['children'].length > 0) {
        let list = treeHandle(item['children'])
        item['budgetDetailUpdateParams']?.forEach((itemChild, index) => {
          itemChild.totalBudget = list.totalList[index]
          itemChild['usedBudget'] = list.usedBudgetList[index] || 0

          totalList[index] = (totalList[index] || 0) + list.totalList[index]
          usedBudgetList[index] = (usedBudgetList[index] || 0) + list.usedBudgetList[index] || 0
        })

        // 解决父节点横向合集
        item['totalMoney'] = list.totalList.reduce((a, b) => {
          return a + b
        }, 0)
        item['totalUsedBudget'] = list.usedBudgetList.reduce((a, b) => {
          return a + b
        }, 0)

      } else {
        item['totalMoney'] = 0
        item['totalUsedBudget'] = 0


        if (!item.budgetDetailUpdateParams) {
          item['budgetDetailUpdateParams'] = addDetailParmas([item])
        }
        item['budgetDetailUpdateParams']?.forEach((itemChild, index) => {

          totalList[index] = (totalList[index] || 0) + (itemChild.totalBudget * 1)
          usedBudgetList[index] = (usedBudgetList[index] || 0) + (itemChild.usedBudget * 1)

          item['totalMoney'] += (itemChild.totalBudget * 1)
          item['totalUsedBudget'] += (itemChild.usedBudget * 1)

        })
      }



    })
    return {
      totalList,
      usedBudgetList
    }
  }
  treeHandle(data)

  return data



}



</script>

<style lang="scss" scoped>
.table {
  width: 100%;
  overflow-x: auto;
  height: calc(100vh - 350px);

}

.table-box {
  width: 101%;
  overflow-x: auto;

  thead {
    height: 58px;
    background: #f8fafc;

    tr {
      position: relative;

      th {
        text-align: left;
        color: #000000;
        font-size: 15px;
        padding: 12px 16px;

      }
    }
  }

  tbody {
    height: 58px;
    background: #fff;

    tr {
      cursor: pointer;

      td {
        text-align: left;
        color: rgb(96, 98, 102);
        font-size: 15px;
        padding: 0 16px;
        border-bottom: 1px solid #ebeef5;
      }
    }
  }
}

.fixed {
  position: sticky !important;
  right: 0;
  background-color: #F8FAFC;
  z-index: 10;

}

.fixed-left {
  position: sticky !important;
  left: 0;
  background-color: #F8FAFC;
  z-index: 10;
}

.fixed-top {
  position: sticky !important;
  top: 0;
  background-color: #F8FAFC;
  z-index: 15;
}

.btn-box {
  text-align: left;
  margin-top: 20px;
  margin-bottom: 15px;
}

.demo-tabs {
  margin-bottom: 15px;
}



.prompt {
  font-size: 14px;
  color: #606266;
}

.table-title {
  display: flex;
  justify-content: space-between;
  align-items: center;

  span {
    flex: 1;
    margin-right: 5px;
  }
}

.small-title {
  font-weight: bold;
  color: #000000 !important;
  font-size: 14px !important;

}

.child-title {
  // padding-left: 28px !important;
  font-size: 13px !important;
}

.privew {
  ul {
    list-style: none;
    padding: 0;
    margin: 0;

    li {

      border-bottom: 1px solid #ebeef5;

      &:nth-child(1) {
        padding-bottom: 10px;
      }

      &:nth-child(2) {
        padding-top: 10px;
        border-bottom: none
      }

      p {
        padding: 0;
        margin: 0;

        &:nth-child(1) {
          margin-bottom: 5px;
        }

      }
    }
  }
}

.use {
  font-size: 14px;
  margin: 5px 0;
  color: #999;

  .link {
    color: #1865f2;
    text-decoration: underline;
  }
}



.box-card {
  margin-top: 20px;

  ::v-deep .el-card__body {
    padding-bottom: 0;
  }

  ::v-deep .el-form-item__label {
    font-size: 15px;
    padding-right: 1px;
  }

  ::v-deep .el-form-item {
    margin-right: 20px;
  }
}

.search-box {
  margin-top: 20px;
}
</style>
